// 微信JSAPI支付实现（基于官方文档最佳实践）
import { wechatJsapiPay } from '@/API/alpayApis.js';
import { loadWeChatSDK, initWxSdk, getWxSignature } from '@/utils/wx-share.js';

/**
 * 微信JSAPI支付（稳定版）
 * @param {Object} options 支付选项
 */
export const wechatPayment = async (options) => {
    try {
        const { days, amount, openid } = options;
        
        // 1. 构建支付请求
        const payData = {
            body: `VIP会员-${days}天`,
            outTradeNo: generateOrderNo(),
            totalFee: Math.round(amount * 100),
            spbillCreateIp: '用户IP',
            openid: openid
        };

        // 2. 调用后端支付接口
        const result = await wechatJsapiPay(payData);
        let paymentData = null;
        
        if (result.code === 200) {
            paymentData = result.data;
        } else if (result.success) {
            paymentData = result.data;
        } else {
            throw new Error(result.message || result.msg || '支付接口调用失败');
        }

        // 3. 确保微信JS-SDK已加载
        await loadWeChatSDK();
        
        // 4. 获取签名配置
        const currentUrl = await getCurrentPageUrl();
        const signatureConfig = await getWxSignature(currentUrl);
        
        // 5. 初始化微信JS-SDK
        await initWxSdk(signatureConfig);
        
        // 6. 调用支付
        const paymentResult = await callWechatPay(paymentData);
        
        return { 
            success: true, 
            data: paymentData,
            result: paymentResult
        };

    } catch (error) {
        console.error('微信支付失败:', error);
        throw error;
    }
};

/**
 * 调用微信支付（核心方法）
 */
const callWechatPay = (paymentData) => {
    return new Promise((resolve, reject) => {
        // 使用wx.ready确保SDK完全就绪
        if (typeof wx !== 'undefined' && typeof wx.ready === 'function') {
            wx.ready(() => {
                executePayment(paymentData, resolve, reject);
            });
        
        } else {
            // 直接执行支付
            executePayment(paymentData, resolve, reject);
        }
    });
};

/**
 * 执行支付操作
 */
const executePayment = (paymentData, resolve, reject) => {
    try {
        // 使用chooseWXPay方法调用支付
        if (typeof wx.chooseWXPay === 'function') {
            wx.chooseWXPay({
                timestamp: paymentData.timeStamp,
                nonceStr: paymentData.nonceStr,
                package: paymentData.packageValue,
                signType: paymentData.signType || 'MD5',
                paySign: paymentData.paySign,
                success: (res) => {
                    resolve(res);
                },
                fail: (err) => {
                    reject(err);
                }
            });
        } else {
            throw new Error('微信支付功能不可用');
        }
    } catch (error) {
        reject(error);
    }
};

/**
 * 获取当前页面URL（uni-app兼容）
 */
const getCurrentPageUrl = () => {
    return new Promise((resolve) => {
        try {
            // uni-app环境获取页面路径
            if (typeof getCurrentPages === 'function') {
                const pages = getCurrentPages();
                if (pages.length > 0) {
                    const route = pages[pages.length - 1].route;
                    resolve(`https://min.erkantv.cn/${route}`);
                    return;
                }
            }
        } catch (error) {
            console.warn('获取页面路径失败:', error);
        }
        
        // 默认URL
        resolve('https://min.erkantv.cn/pages/alpay/alpay');
    });
};

/**
 * 生成订单号
 */
const generateOrderNo = () => {
    return 'WXPAY_' + Date.now() + '_' + Math.random().toString(36).substr(2, 6);
};

/**
 * 处理支付结果
 */
export const handlePaymentResult = (result) => {
    if (result && result.success) {
        uni.showToast({ title: '支付成功', icon: 'success' });
        return true;
    } else {
        let errorMessage = '支付失败';
        if (result && result.error) {
            if (result.error.errMsg && result.error.errMsg.includes('cancel')) {
                errorMessage = '用户取消支付';
                  uni.showToast({ title: '用户取消支付', icon: 'success' });
            }
        }
        uni.showToast({ title: errorMessage, icon: 'none' });
        return false;
    }
};

export default {
    wechatPayment,
    handlePaymentResult
};